package com.java.service.impl;

import com.java.entity.Blog;
import com.java.entity.BlogType;
import com.java.entity.Blogger;
import com.java.entity.Link;
import com.java.service.BlogService;
import com.java.service.BlogTypeService;
import com.java.service.BloggerService;
import com.java.service.LinkService;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import java.util.List;

/**
 * 初始化InitComponent实现类
 * @author wmx
 * @create 2020-03-08 16:14
 */
@Component
public class InitComponent implements ServletContextListener, ApplicationContextAware {


    // applicationContext上下文
   private static ApplicationContext applicationContext;

   //初始化application，将获取到的信息存到application中
    @Override
    public void contextInitialized(ServletContextEvent servletContextEvent) {
        ServletContext application = servletContextEvent.getServletContext();
        //通过applicationContent上下文获取博主实现类
        BloggerService bloggerService = (BloggerService) applicationContext.getBean("bloggerService");
        Blogger blogger = bloggerService.getBlogger();
        //将博主信息放到application中
        blogger.setPassword(null);
        application.setAttribute("blogger",blogger);
        LinkService linkService = (LinkService) applicationContext.getBean("linkService");
        List<Link> linkList = linkService.getLink(null);
        //将友情链接信息放到application中
        application.setAttribute("linkList",linkList);
        BlogTypeService blogTypeService = (BlogTypeService) applicationContext.getBean("blogTypeService");
        List<BlogType> blogTypeList = blogTypeService.getBlogType();
        //将博客类型信息放到application中
        application.setAttribute("blogTypeList",blogTypeList);
        BlogService blogService = (BlogService) applicationContext.getBean("blogService");
        List<Blog> blogList = blogService.getBlog();
        //将博客信息(按日期分类)放到application中
        application.setAttribute("blogDateList",blogList);


    }

    @Override
    public void contextDestroyed(ServletContextEvent servletContextEvent) {

    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
       this.applicationContext = applicationContext;
    }
}
